# -*- coding: utf-8 -*-
"""
    author: Ye
    date: 2021/1/28 13:58 
"""
from flask import Blueprint, request, jsonify, g
from flask.views import MethodView
from models.user import UserExtend, User
from utils import response_err
from utils.token_jwt import get_token
from utils.permission import user_required
from forms.user_schema import UserSchema
from extensions import db

user_bp = Blueprint('user', __name__)


@user_bp.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    print(username)
    user = User.query.filter_by(username=username).first()
    if user:
        if user.check_password(password):
            token = get_token(username=username, user_id=user.id)
            return jsonify({'code': 0, 'msg': '', 'token': token})
        else:
            raise response_err.Error401(msg='密码有误')
    else:
        raise response_err.Error401(msg='用户名不存在')


@user_bp.route('/register', methods=['POST'])
def register():
    user_schema = UserSchema()
    user = user_schema.load(request.form,session=db.session)
    print(user)
    db.session.add(user)
    db.session.commit()
    token = get_token(username=user.username, user_id=user.id)
    return jsonify({'code': 0, 'msg': '注册成功', 'token': token})


@user_bp.route('/token/reset', methods=['POST'])
@user_required
def token_reset():
    username = g.username
    user_id = g.user_id
    token = get_token(username=username, user_id=user_id)
    return jsonify({'code': 0, 'msg': '', 'token': token})


@user_bp.route('/token/reset1512121212121', methods=['POST'])
@user_required
def token_reset():
    username = g.username
    user_id = g.user_id
    token = get_token(username=username, user_id=user_id)
    return jsonify({'code': 0, 'msg': '', 'token': token})